import sys
import os
import re
from docx import Document
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
                             QLabel, QLineEdit, QPushButton, QFileDialog, QMessageBox,
                             QProgressBar, QGroupBox, QSizePolicy)
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QFont, QIcon

class TranslationRemoverApp(QMainWindow):
    def __init__(self):
        super().__init__()
        self.default_regex = r'\s+[a-z.]+\.\s*.*$'
        self.supported_formats = ['.docx', '.txt']
        self.initUI()
        self.setWindowIcon(QIcon('icon.png'))  # 准备一个图标文件或移除这行

    def initUI(self):
        self.setWindowTitle('单词翻译去除器')
        self.setGeometry(300, 300, 650, 400)
        self.setStyleSheet("""
            QMainWindow { background-color: #f0f4f7; }
            QGroupBox { 
                background-color: white;
                border: 2px solid #2196F3;
                border-radius: 8px;
                margin-top: 10px;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                left: 10px;
                padding: 0 3px;
                color: #2196F3;
            }
            QPushButton {
                background-color: #2196F3;
                color: white;
                border: none;
                padding: 8px 16px;
                border-radius: 4px;
                font-size: 14px;
            }
            QPushButton:hover { background-color: #1976D2; }
            QLineEdit { 
                border: 1px solid #cccccc;
                padding: 6px;
                border-radius: 4px;
            }
            QProgressBar {
                border: 1px solid #2196F3;
                border-radius: 4px;
                text-align: center;
            }
            QProgressBar::chunk {
                background-color: #2196F3;
                width: 10px;
            }
        """)

        # 创建主控件
        main_widget = QWidget()
        self.setCentralWidget(main_widget)
        main_layout = QVBoxLayout(main_widget)

        # 文件选择组
        file_group = QGroupBox("文件操作")
        file_layout = QVBoxLayout()

        # 输入文件选择
        input_layout = QHBoxLayout()
        self.input_path = QLineEdit()
        self.input_path.setPlaceholderText("请选择要处理的文档（支持.docx和.txt）...")
        btn_browse = QPushButton("浏览文件")
        btn_browse.clicked.connect(self.select_file)
        input_layout.addWidget(self.input_path)
        input_layout.addWidget(btn_browse)

        # 输出文件设置
        output_layout = QHBoxLayout()
        self.output_path = QLineEdit()
        self.output_path.setPlaceholderText("自动生成输出路径...")
        btn_output = QPushButton("另存为")
        btn_output.clicked.connect(self.set_output_path)
        output_layout.addWidget(self.output_path)
        output_layout.addWidget(btn_output)

        file_layout.addLayout(input_layout)
        file_layout.addLayout(output_layout)
        file_group.setLayout(file_layout)

        # 正则表达式组
        regex_group = QGroupBox("正则表达式设置")
        regex_layout = QVBoxLayout()

        self.regex_edit = QLineEdit()
        self.regex_edit.setText(self.default_regex)
        btn_default = QPushButton("恢复默认正则")
        btn_default.clicked.connect(self.set_default_regex)

        regex_layout.addWidget(QLabel("匹配模式:"))
        regex_layout.addWidget(self.regex_edit)
        regex_layout.addWidget(btn_default)
        regex_group.setLayout(regex_layout)

        # 进度条
        self.progress = QProgressBar()
        self.progress.setAlignment(Qt.AlignCenter)
        self.progress.setVisible(False)

        # 操作按钮
        btn_process = QPushButton("开始处理文件")
        btn_process.clicked.connect(self.process_document)
        btn_process.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)

        # 组装主界面
        main_layout.addWidget(file_group)
        main_layout.addWidget(regex_group)
        main_layout.addWidget(self.progress)
        main_layout.addWidget(btn_process)

    def select_file(self):
        file_path, _ = QFileDialog.getOpenFileName(
            self, "选择文件", "", 
            "支持的文件类型 ({})".format(" ".join(["*"+ext for ext in self.supported_formats]))
        )
        if file_path:
            self.input_path.setText(file_path)
            base_name = os.path.splitext(file_path)[0]
            self.output_path.setText(f"{base_name}(处理后){os.path.splitext(file_path)[1]}")

    def set_output_path(self):
        current_ext = os.path.splitext(self.input_path.text())[1] if self.input_path.text() else ".docx"
        save_path, _ = QFileDialog.getSaveFileName(
            self, "保存处理结果", 
            self.output_path.text(),
            "支持的文件类型 ({})".format(" ".join(["*"+ext for ext in self.supported_formats]))
        )
        if save_path:
            # 确保文件扩展名正确
            ext = os.path.splitext(save_path)[1].lower()
            if ext not in self.supported_formats:
                save_path += current_ext
            self.output_path.setText(save_path)

    def set_default_regex(self):
        self.regex_edit.setText(self.default_regex)

    def validate_inputs(self):
        if not self.input_path.text():
            QMessageBox.warning(self, "输入错误", "请先选择要处理的文件")
            return False
        
        file_ext = os.path.splitext(self.input_path.text())[1].lower()
        if file_ext not in self.supported_formats:
            QMessageBox.warning(self, "格式错误", 
                f"不支持的文件格式：{file_ext}\n支持格式：{', '.join(self.supported_formats)}")
            return False

        if not self.output_path.text():
            QMessageBox.warning(self, "输出错误", "请指定输出文件路径")
            return False
        
        try:
            re.compile(self.regex_edit.text())
            return True
        except re.error as e:
            QMessageBox.critical(self, "正则表达式错误", f"无效的正则表达式:\n{str(e)}")
            return False

    def process_document(self):
        if not self.validate_inputs():
            return

        input_file = self.input_path.text()
        output_file = self.output_path.text()
        pattern = re.compile(self.regex_edit.text())
        file_ext = os.path.splitext(input_file)[1].lower()

        try:
            self.progress.setVisible(True)
            self.setCursor(Qt.WaitCursor)

            if file_ext == '.docx':
                self.process_docx(input_file, output_file, pattern)
            elif file_ext == '.txt':
                self.process_txt(input_file, output_file, pattern)
            
            QMessageBox.information(self, "处理完成", 
                f"文件处理成功！\n保存路径: {output_file}")
            
        except Exception as e:
            QMessageBox.critical(self, "处理错误", 
                f"处理过程中发生错误:\n{str(e)}")
        finally:
            self.progress.reset()
            self.progress.setVisible(False)
            self.unsetCursor()

    def process_docx(self, input_path, output_path, pattern):
        doc = Document(input_path)
        total = len(doc.paragraphs)
        self.progress.setMaximum(total)

        for i, para in enumerate(doc.paragraphs):
            if para.text.strip():
                para.text = pattern.sub('', para.text).strip()
            self.progress.setValue(i+1)
            QApplication.processEvents()

        doc.save(output_path)

    def process_txt(self, input_path, output_path, pattern):
        # 自动检测编码
        encodings = ['utf-8', 'gbk', 'gb2312', 'big5']
        content = []
        for enc in encodings:
            try:
                with open(input_path, 'r', encoding=enc) as f:
                    content = f.readlines()
                break
            except UnicodeDecodeError:
                continue
        
        if not content:
            raise ValueError("无法自动检测文件编码")

        total = len(content)
        self.progress.setMaximum(total)

        processed_lines = []
        for i, line in enumerate(content):
            processed_lines.append(pattern.sub('', line).strip() + '\n')
            self.progress.setValue(i+1)
            QApplication.processEvents()

        with open(output_path, 'w', encoding='utf-8') as f:
            f.writelines(processed_lines)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    app.setFont(QFont("微软雅黑", 10))
    window = TranslationRemoverApp()
    window.show()
    sys.exit(app.exec_())